jQuery.delProduct = function(id)
{
	$.ajax({
		url     : $.url('/auth/delproduct'),
		type    : 'POST',
		dataType: 'json',
		data    : { id: id },
		success : function(data, textStatus, XMLHttpRequest) {
			if(data.status === true) {
				var id = parseInt(data.data.id);
				$('.cart-table > table > tbody > tr').filter(function() { return $(this).attr('prod-id') == id; }).detach();
				$('#top-panel > #cart').html(data.data.cartHtml);
				if(data.data.redirect) window.location.reload();
				$('.total-price').html(data.data.total);
			}
		},
		error   : function(XMLHttpRequest, textStatus, errorThrown) {
			console.error(XMLHttpRequest.responseText);
		}
	});
}

jQuery.fn.control = function()
{
	$.each(this, function() {
		$(this).keypress(function() {
			var input = this;
			setTimeout(function(){
				var val = parseInt($(input).val());
				if((val !== val) || (val < 1) || (val > 100)) val = 1;
				$(input).val(val)
			}, 500)
		});
	});
}

jQuery.sync = function() 
{
	var data = {};
	$.each($('.cart-table > table > tbody > tr'), function() {
		var id    = parseInt($(this).attr('prod-id'));
		var count = parseInt($(this).find('.quantity input').val());
		data[id] = count;
	});
	$.ajax({
		url     : $.url('/auth/saveproduct'),
		type    : 'POST',
		dataType: 'json',
		data    : { data: data },
		success : function(data, textStatus, XMLHttpRequest) {
			if(data.status === true) {
				$('#cart').html(data.data.cartHtml);
				$('.total-price').html(data.data.total);
			}
		},
		error   : function(XMLHttpRequest, textStatus, errorThrown) {
			console.error(XMLHttpRequest.responseText);
		}
	});
}

$(function(){
	$('.delete-but').click(function(){
		var id = parseInt($(this).parents('.product').attr('prod-id'));
		$.delProduct(id);
	});
	$('.quantity > input').control();
	$('.recalc').click($.sync);
});